import SockJS from 'sockjs-client';
import store from '@/vuex/store.js'
var ws;//websocket实例
var lockReconnect = false;//避免重复连接
var wsUrl = 'ws://192.168.3.102:16000/elderly/ws.do?Authorization='+localStorage.userid + '_' + store.state.token+"&&userName="+localStorage.username;
// var wsUrl = 'ws://221.236.172.57:16000/elderly/ws.do?Authorization='+localStorage.userid + '_' + store.state.token+"&&userName="+localStorage.username;
function createWebSocket(url) {//创建webscoket
  try {
    ws = new WebSocket(url);
    initEventHandle();
  } catch (e) {
    reconnect(url);
  }
}
function initEventHandle() {//断线重连
  ws.onclose = function () {
    reconnect(wsUrl);
    console.log("close")
  };
  ws.onerror = function () {
    reconnect(wsUrl);
    console.log("close")
  };
  ws.onopen = function () {
    //心跳检测重置
    heartCheck.reset().start();
    console.log("open")
  };
  ws.onmessage = function (event) {
    //如果获取到消息，心跳检测重置
    //拿到任何消息都说明当前连接是正常的
    heartCheck.reset().start();
  }
}
function reconnect(url) {
  if(lockReconnect) return;
  lockReconnect = true;
  store.commit("socketStatus", lockReconnect)
  //没连接上会一直重连，设置延迟避免请求过多
  setTimeout(function () {
    createWebSocket(url);
    lockReconnect = false;
    store.commit("socketStatus", lockReconnect)
  }, 2000);
}
//心跳检测
var heartCheck = {
  timeout: 60000,//60秒
  timeoutObj: null,
  serverTimeoutObj: null,
  reset: function(){
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    return this;
  },
  start: function(){
    var self = this;
    this.timeoutObj = setTimeout(function(){
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      //onmessage拿到返回的心跳就说明连接正常
      ws.send("HeartBeat");
      self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
        ws.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
      }, self.timeout)
    }, this.timeout)
  }
}
createWebSocket(wsUrl);
// 处理消息时
var getMsg=function(){
  ws.onmessage = function (evnt) {
    heartCheck.reset().start();
    if(typeof(evnt.data)=="string"){//文字
      store.commit("msgText", null)
      setTimeout(() => {
        store.commit("msgText", JSON.parse(evnt.data))
        // console.log(evnt.data)
      },500);
    }
  };
}
var sendText=function(msg){//发送消息
  ws.send(JSON.stringify(msg));
};
var sendFile=function(file,status){//参数为input->file,第二个参数为是否携带参数
  var reader = new FileReader();
  //以二进制形式读取文件
  reader.readAsArrayBuffer(file);
  //文件读取完毕后该函数响应
  reader.onload = function loaded(evt) {
    var blob = evt.target.result;
    var msg={
      msgContent: file.type,//发送内容
      postsId:"type"
    }
    ws.send(JSON.stringify(msg));
    // console.log(blob)
    //发送二进制表示的文件
    ws.send(blob);
    // ws.send(file.type+":fileFinishWithText");//携带参数的文件
    // if(status){
    //     ws.send(file.type+":fileFinishWithText");//携带参数的文件
    // }else{
    //     ws.send(file.type+":fileFinishSingle"); //不带参数为单独文件
    //     console.log("111");
    // }
    store.commit("sendstatus",0)
    console.log("success");
    //var data = new Uint8Array(evt.target.result);
    //websocket.send(data);
  }
}

var vun={
  getMsg,
  sendText,
  sendFile,
}
export{
  vun
}
